<template>
  <div>
    <!-- 商品列表表格 -->
    <el-table
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      ref="multipleTableRef"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="name" label="商品名称" />
      <el-table-column prop="category" label="商品分类" />
      <el-table-column prop="price" label="商品价格" />
      <el-table-column label="商品图片">
        <template #default="scope">
          <el-image
            style="width: 50px; height: 50px"
            :src="`api/${scope.row.imgUrl}`"
            :preview-src-list="['api/' + scope.row.imgUrl]"
            preview-teleported
          />
        </template>
      </el-table-column>
      <el-table-column prop="goodsDesc" label="商品描述" />
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editForm.id ? '编辑商品' : '新增商品'"
      width="50%"
    >
      <el-form :model="editForm" label-width="120px">
        <el-form-item label="商品名称" required>
          <el-input v-model="editForm.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品分类" required>
          <el-input v-model="editForm.category" placeholder="请输入商品分类" />
        </el-form-item>
        <el-form-item label="商品价格" required>
          <el-input-number v-model="editForm.price" :precision="2" :step="0.1" :min="0" />
        </el-form-item>
        <el-form-item label="商品图片">
          <el-upload
            class="avatar-uploader"
            action="/api/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
          >
            <img v-if="editForm.imgUrl" :src="editForm.imgUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品描述">
          <el-input
            v-model="editForm.goodsDesc"
            type="textarea"
            placeholder="请输入商品描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, onMounted, reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { list, del, edit } from '@/views/api/goods.js';

// 数据列表
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(5);
const multipleTableRef = ref(null);
const selectedRows = ref([]);

// 编辑表单相关
const dialogVisible = ref(false);
const editForm = ref({
  id: '',
  name: '',
  category: '',
  price: '',
  imgUrl: '',
  goodsDesc: ''
});

// 表单数据
const formData = reactive({
  currentPage: 1,
  pageSize: 5
});

// 获取商品列表
const getGoodsList = async () => {
  try {
    const res = await list({
      currentPage: formData.currentPage,
      pageSize: formData.pageSize
    });
    tableData.value = res.data;
    total.value = res.total;
  } catch (error) {
    ElMessage.error('获取商品列表失败');
  }
};

// 处理页码变化
const handleCurrentChange = (val) => {
  formData.currentPage = val;
  getGoodsList();
};

// 处理每页条数变化
const handleSizeChange = (val) => {
  formData.pageSize = val;
  getGoodsList();
};

// 处理选择变化
const handleSelectionChange = (rows) => {
  selectedRows.value = rows.map(row => row.id);
};

// 处理编辑
const handleEdit = (row) => {
  editForm.value = { ...row };
  dialogVisible.value = true;
};

// 处理删除
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确认要删除该商品吗？', '提示', {
      type: 'warning'
    });
    const res = await del({ id });
    if (res.code === 0) {
      ElMessage.success('删除成功');
      getGoodsList();
    } else {
      ElMessage.error(res.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 处理保存
const handleSave = async () => {
  try {
    const res = await edit(editForm.value);
    if (res.code === 0) {
      ElMessage.success('保存成功');
      dialogVisible.value = false;
      getGoodsList();
    } else {
      ElMessage.error(res.msg || '保存失败');
    }
  } catch (error) {
    ElMessage.error('保存失败');
  }
};

// 处理图片上传成功
const handleAvatarSuccess = (res) => {
  if (res.code === 0) {
    editForm.value.imgUrl = res.data;
  } else {
    ElMessage.error(res.msg || '上传失败');
  }
};

// 页面加载时获取列表
onMounted(() => {
  getGoodsList();
});
</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>